package com.qyhl.webtv.module_circle.circle.add;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.view.MotionEventCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.common.CircleUtils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;

/**
 * 添加圈子
 *
 * @author helin
 */
@Route(path = ARouterPathConstant.CIRCLE_ADD)
public class AddCircleActivity extends BaseActivity implements AddCircleContract.AddCircleView {

    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 188;
    /**
     * 文本内容
     */
    @BindView(R2.id.add_circle_content)
    EditText mAddCircleContent;
    /**
     * 图片
     */
    @BindView(R2.id.add_circle_image)
    RecyclerView mAddCircleImage;
    /**
     * 位置
     */
    @BindView(R2.id.add_circle_location)
    TextView mAddCircleLocation;

    /**
     * 标签列表
     */
    @BindView(R2.id.add_circle_tags)
    TagFlowLayout mCircleTags;

    /**
     * 视频选择layout
     */
    @BindView(R2.id.add_video_layout)
    LinearLayout mAddVideoLayout;

    /**
     * 视频预览界面
     */
    @BindView(R2.id.video_cover_layout)
    FrameLayout mVideoYu;

    /**
     * 视频封面
     */
    @BindView(R2.id.video_cover_img)
    ImageView mVideoCover;
    @BindView(R2.id.taglist_layout)
    LinearLayout taglistLayout;

    @BindView(R2.id.add_circle_content_num)
    TextView contentNum;


    /**
     * 空数据
     */
    private LocalMedia addMde;
    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();
    /**
     * 图片选择适配器
     */
    private RecyclerViewAdatper mImageAdapter;
    /**
     * 控制器
     */
    private AddCirclePresenter mPresenter;
    /**
     * 类型
     */
    int mType = 0;
    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    /**
     * 标签数据
     */
    private List<CircleHomeBean.TagList> mTagsData;

    /**
     * 视频选择
     */
    public static final int CHOOSE_VIDEO = 191;

    /**
     * 位置信息
     */
    String postionStr = "";
    /**
     * 所选标签
     */
    private StringBuffer tagIds;

    /**
     * 声明AMapLocationClient类对象
     */
    public AMapLocationClient mLocationClient = null;
    /**
     * 声明AMapLocationClientOption对象
     */
    public AMapLocationClientOption mLocationOption = null;
    /**
     * 视频封面
     */
    private String mVideoCoverPath;
    /**
     * 视频地址
     */
    private String mVideoPath;
    /**
     * 本地视频地址
     */
    private String mLocalVideo;


    String tagId;

    private int checkType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.circle_activity_add_circle;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new AddCirclePresenter(this);
        mType = getIntent().getIntExtra("type", 0);
        tagId = getIntent().getStringExtra("id");
        initView();
        mPresenter.getCheckType(false);
        //获取上传token
        mPresenter.getToken();
    }

    @Override
    protected void setListener() {

    }


    private void initView() {
        tagIds = new StringBuffer();
        if (mType == 1 || mType == 3 || mType == 5) {
            //图文圈子
            mAddCircleImage.setVisibility(View.VISIBLE);
            mAddVideoLayout.setVisibility(View.GONE);
        } else {
            //视频+图文圈子
            mAddVideoLayout.setVisibility(View.VISIBLE);
            mAddCircleImage.setVisibility(View.GONE);
        }
        //添加最有一个图片
        addMde = new LocalMedia();
        addMde.setPath("1");
        selectedList.add(addMde);

        mAddCircleImage.setLayoutManager(new GridLayoutManager(this, 3));
        mAddCircleImage.setItemAnimator(new DefaultItemAnimator());
        mAddCircleImage.setAdapter(mImageAdapter = new RecyclerViewAdatper());

        mAddCircleContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                contentNum.setText(s.length() + "/500");
            }
        });



        if (mType == 5 || mType == 6) {
            taglistLayout.setVisibility(View.GONE);
            mCircleTags.setVisibility(View.GONE);
            tagIds.append(tagId);
        } else {
            taglistLayout.setVisibility(View.VISIBLE);
            mCircleTags.setVisibility(View.VISIBLE);
            showSimpleLoading();
            mPresenter.getTagList();
        }

    }

    int mPro = 0;

    /**
     * 检查数据
     */
    private void checkData() {
        if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
            showToast("用户信息审核中，暂时无法使用该功能！", INFO);
            return;
        }

        if (checkType == 0) {
            Toasty.normal(this, "服务器连接失败！").show();
            return;
        }
        final String content = mAddCircleContent.getText().toString();
        if (StringUtils.isEmpty(content) && selectedList.size() == 1 && StringUtils.isEmpty(mLocalVideo)) {
            showToast("不能发布空内容", INFO);
            return;
        }
        //获取标签
        Set<Integer> tagsList = mCircleTags.getSelectedList();
        for (int postion : tagsList) {
            int id = mTagsData.get(postion).getId();
            tagIds.append(id).append(",");
        }

        //视频类型
        if (mType == 2 || mType == 4 || mType == 6) {
            if (StringUtils.isEmpty(mLocalVideo)) {
                showSimpleLoading("发布中..");
                mPresenter.postData(content, tagIds, postionStr, 1);
            } else {
//                if (mLocalVideo.contains("qz")) {
                showSimpleLoading("发布中..");
                mVideoPath = mLocalVideo;
                upLoadVideo();
//                } else {
//                    compressVideo(mLocalVideo);
//                }

            }
            return;
        }

        if (selectedList.size() == 1) {
            showSimpleLoading("发布中..");
            mPresenter.postData(content, tagIds, postionStr, 1);
            return;
        }
        showHorizontalSimpleLoading("uploadImage");
        if (mUpToken == null) {
            mPresenter.getToken();
            return;
        }
        upLoadImage();
    }


    /**
     * 定位
     */
    private void location() {
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(15000);
        mLocationOption.setInterval(2000);
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mAddCircleLocation.setText("定位中...");
        mLocationClient.startLocation();
    }

    /**
     * 声明定位回调监听器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    postionStr = aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + aMapLocation.getAoiName() + aMapLocation.getBuildingId();
                    mAddCircleLocation.setText(postionStr);
                } else {
                    mAddCircleLocation.setText("定位失败!");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                }
            }
            mLocationClient.stopLocation();
        }
    };


    /**
     * 删除已选视频
     */
    private void deleteVideo() {
        //删除视频文件
        mVideoCoverPath = "";
        mVideoPath = "";
        mLocalVideo = "";
        mVideoYu.setVisibility(View.GONE);
    }

    /**
     * 选择视频
     */
    private void chooseVideo() {
        int maxTime;
        if (CommonUtils.getInstance().getSite() == 176) {
            maxTime = 120;
        } else if (CommonUtils.getInstance().getSite() == 148) {
            maxTime = 180;
        } else {
            maxTime = 15;
        }
        PictureSelector.create(AddCircleActivity.this)
                .openGallery(PictureMimeType.ofVideo())
                .imageSpanCount(4)
                .previewVideo(true)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .isCamera(true)
                .isZoomAnim(true)
                .compress(true)
                .videoMaxSecond(maxTime)
                .videoMinSecond(2)
                .videoQuality(1)
                .recordVideoSecond(maxTime)
                .forResult(CHOOSE_VIDEO);
    }

    /**
     * 图片多选
     */
    private void chooseImage() {
        PictureSelector.create(AddCircleActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_REQUEST);
    }

    /**
     * 预览视频
     */
    private void previewVideo() {
        Bundle bundle = new Bundle();
        bundle.putString(IntentKey_VideoUrl, mLocalVideo);
        bundle.putString(IntentKey_VideoCover, mVideoCoverPath);
        RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
    }

    /**
     * 获取视频封面图
     */
    public void getPicture(String path) {
        File file = new File(path);
        //判断对象是否存在，不存在的话给出Toast提示
        if (file.exists()) {
            //提供统一的接口用于从一个输入媒体中取得帧和元数据
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(path);
            Bitmap bitmap = retriever.getFrameAtTime();
            String dirpath = Environment.getExternalStorageDirectory().getPath() + CircleUtils.PIC;
            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString() + ".png";
            mVideoCoverPath = Environment.getExternalStorageDirectory().getPath() + CircleUtils.PIC + File.separator + name;
            Glide.with(AddCircleActivity.this)
                    .load(mVideoCoverPath)
                    .into(mVideoCover);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mVideoCoverPath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("生成封面图失败", INFO);
            }
        } else {
            showToast("视频路径不存在", INFO);
        }
    }

    /**
     * 上传视频
     */
    private void upLoadVideo() {
        final String content = mAddCircleContent.getText().toString();
        List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
        UploadBean videoBean = new UploadBean();
        videoBean.setType(3);
        videoBean.setPath(mVideoPath);
        videoBean.setPostion(0);
        uploadBeans.add(videoBean);

        UploadBean videoCoverBean = new UploadBean();
        videoCoverBean.setType(4);
        videoCoverBean.setPath(mVideoCoverPath);
        videoCoverBean.setPostion(0);
        uploadBeans.add(videoCoverBean);

        final int maxPro = uploadBeans.size();
        QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getUptoken(), mUpToken.getPrefix(), new UploadResultListener() {
            @Override
            public void uplaodError() {
                dismissLoading();
                showToast("上传图片出错", INFO);
            }

            @Override
            public void uploadSuccess(List<UploadBean> files) {
                mPresenter.combinationVideoData(content, tagIds.toString(), postionStr, 3, files);
            }

            @Override
            public void uploadPre(double percent) {
                setPro((int) percent);
            }
        });
    }

    /**
     * 上传图片
     */
    private void upLoadImage() {
        final String content = mAddCircleContent.getText().toString();
        List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
        if (selectedList.size() != 0) {
            for (int i = 0; i < selectedList.size() - 1; i++) {
                LocalMedia image = selectedList.get(i);
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(image.getCompressPath());
                videoCoverBean.setPostion(0);
                videoCoverBean.setIndex(i);
                uploadBeans.add(videoCoverBean);
            }
        }
        QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getUptoken(), mUpToken.getPrefix(), new UploadResultListener() {
            @Override
            public void uplaodError() {
                dismissLoading();
                showToast("上传图片出错", INFO);
            }

            @Override
            public void uploadSuccess(List<UploadBean> files) {
                mPresenter.combinationData(content, tagIds.toString(), postionStr, 2, files);
            }

            @Override
            public void uploadPre(double percent) {
                setPro((int) percent);
            }
        });
    }

//    /**
//     * 压缩视频
//     */
//    private void compressVideo(String path) {
//        showLoading("压缩视频中...");
//        //获取视频封面
//        getPicture(path);
//        String cacheUrl = getExternalCacheDir().getPath();
//        String fileName = UUID.randomUUID().toString();
//        final String outPath = cacheUrl + "/" + fileName + ".mp4";
//
//        VideoCompress.compressVideo(path, outPath, new VideoCompressCallBack() {
//            @Override
//            public void onSuccess() {
//                mVideoPath = outPath;
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Glide.with(AddCircleActivity.this)
//                                .load(mVideoCoverPath)
//                                .into(mVideoCover);
//                        dismissLoading();
//                        showHorizontalSimpleLoading("uploadImage");
//                        if (mUpToken == null) {
//                            mPresenter.getToken();
//                            return;
//                        }
//                        upLoadVideo();
//
//                    }
//                });
//            }
//
//            @Override
//            public void onError() {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        dismissLoading();
//                        showToast("压缩失败", INFO);
//                    }
//                });
//            }
//
//            @Override
//            public void onPre(int pre) {
//
//            }
//        });
//    }


    @Override
    public void getTagError() {
        dismissLoading();
        showToast("获取标签失败", INFO);
    }

    @Override
    public void getTagSuccess(List<CircleHomeBean.TagList> data) {
        dismissLoading();
        mTagsData = data;
        mCircleTags.setAdapter(new TagAdapter<CircleHomeBean.TagList>(data) {
            @Override
            public View getView(FlowLayout parent, int position, CircleHomeBean.TagList s) {
                TextView tv = (TextView) LayoutInflater.from(AddCircleActivity.this).inflate(R.layout.circle_item_add_circle_tag,
                        mCircleTags, false);
                tv.setText("#" + s.getName() + "#");
                return tv;
            }
        });

        if (StringUtils.isNotEmpty(tagId)) {
            for (int i = 0; i < mTagsData.size(); i++) {
                if (mTagsData.get(i).getId() == Integer.parseInt(tagId)) {
                    mCircleTags.getAdapter().setSelectedList(i);
                }
            }
        }
    }

    @Override
    public void postError(String msg) {
        dismissLoading();
        showToast(msg, INFO);
    }

    @Override
    public void postSuccess(int topicId) {
        dismissLoading();

        if (checkType == 1) {
            showToast("发布成功,等待审核！", INFO);
        } else {
            showToast("发布成功", INFO);
            int cType = 0;
            List<CircleHomeBean.PicList> picLists = new ArrayList<>();
            if (mType == 2 || mType == 4) {
                cType = 3;
            } else if (selectedList.size() == 1) {
                cType = 1;
            } else {
                if (selectedList.size() != 0) {
                    for (int i = 0; i < selectedList.size() - 1; i++) {
                        picLists.add(new CircleHomeBean.PicList(selectedList.get(i).getCompressPath(), selectedList.get(i).getCompressPath()));
                    }
                }
                cType = 2;
            }

            //获取标签
            List<CircleHomeBean.TagList> tagLists = new ArrayList<>();
            Set<Integer> tagsList = mCircleTags.getSelectedList();
            Iterator<Integer> ite = tagsList.iterator();
            while (ite.hasNext()) {
                int postion = ite.next();
                tagLists.add(new CircleHomeBean.TagList(mTagsData.get(postion).getName(), mTagsData.get(postion).getId()));
            }

            String nickName = CommonUtils.getInstance().getNickName();
            String userName = CommonUtils.getInstance().getUserName();
            String headicon = CommonUtils.getInstance().getUserLogo();
            CircleHomeBean bean = new CircleHomeBean(true, false, false, null, null, 0, cType, mAddCircleContent.getText().toString(), mVideoCoverPath, DateUtils.getCurrentTime()
                    , CommonUtils.getInstance().getSite(), postionStr, topicId, 1, mVideoPath, 0, 0, picLists, null, new CircleHomeBean.User(nickName, headicon, userName, false), null, null, tagLists);
            List<CircleHomeBean> localList;
            if (Hawk.contains("circle_local")) {
                localList = Hawk.get("circle_local");
            } else {
                localList = new ArrayList<>();
            }
            localList.add(bean);
            Hawk.put("circle_local", localList);
            BusFactory.getBus().post(new Event.circleLocalAdd(bean));
        }
        String userName = CommonUtils.getInstance().getUserName();
        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            mPresenter.getCoin(userName);
        } else {
            finish();
        }
    }

    @Override
    public void getTokenError() {
        dismissLoading();
        showToast("获取上传信息失败", INFO);
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUp) {
        mUpToken = data;
        if (isUp) {
            upLoadImage();
        }
    }

    @Override
    public void setCheckType(int typeId, boolean isUp) {
        checkType = typeId;
        if (isUp) {
            checkData();
        }
    }

    @Override
    public void getCoinSuccess(CoinBean bean) {
        Toasty.normal(this, "发布帖子，获得" + bean.getCoin() + "金币！").show();
        finish();
    }

    @Override
    public void getCoinFailure(String msg) {
        Log.i("coin_error", msg);
        finish();
    }

    /**
     * RecyclerViewAdatper
     */
    public class RecyclerViewAdatper extends RecyclerView.Adapter<ViewHolder> {

        RecyclerViewAdatper() {
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.circle_item_content_img_list, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            if (selectedList.get(position).getPath().endsWith("1")) {
                holder.deleteView.setVisibility(View.GONE);
                holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                holder.handleView.setOnTouchListener(null);
            } else {
                holder.deleteView.setVisibility(View.VISIBLE);
                holder.deleteView.setTag(position);
                holder.deleteView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                            selectedList.add(addMde);
                        }
                        int pos = (int) v.getTag();
                        selectedList.remove(pos);
                        mImageAdapter.notifyDataSetChanged();
                    }
                });
                if (position == selectedList.size() - 1) {
                    holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                    holder.handleView.setOnTouchListener(null);
                } else {

                    Glide.with(AddCircleActivity.this).load(selectedList.get(position).getCompressPath()).into(holder.handleView);
                    holder.handleView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                                if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                                    selectedList.add(addMde);
                                }
                            }
                            return false;
                        }
                    });
                }
            }
        }

        @Override
        public int getItemCount() {
            return selectedList.size();
        }
    }


    /**
     * ViewHolder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView handleView;
        public ImageView deleteView;

        public ViewHolder(View itemView) {
            super(itemView);
            handleView = (ImageView) itemView.findViewById(R.id.content_img);
            deleteView = (ImageView) itemView.findViewById(R.id.image_delete);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (selectedList.size() == 0 || !selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                        selectedList.add(addMde);
                    }
                    if (getLayoutPosition() == selectedList.size() - 1) {
                        //弹出选择菜单
                        selectedList.remove(selectedList.size() - 1);
                        chooseImage();
                    } else {

                        ArrayList<String> result = new ArrayList<>();
                        for (int i = 0; i < selectedList.size() - 1; i++) {
                            result.add(selectedList.get(i).getPath());
                        }
                        MNImageBrowser.showImageBrowser(AddCircleActivity.this, view, getLayoutPosition(), result);

                    }
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        switch (requestCode) {
            case CHOOSE_REQUEST:
                resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList != null && resultList.size() > 0) {
                    selectedList.clear();
                    selectedList.addAll(resultList);
                }
                selectedList.add(addMde);
                mImageAdapter.notifyDataSetChanged();
                break;
            case CHOOSE_VIDEO: {
                //视频选择
                List<LocalMedia> pic = PictureSelector.obtainMultipleResult(data);
                if (pic != null && pic.size() > 0) {
                    //视频路径
                    String path = pic.get(0).getPath();
                    getPicture(path);
                    mLocalVideo = path;
                    mVideoYu.setVisibility(View.VISIBLE);
                }
            }
            break;
            default:
                break;
        }
    }

    @OnClick({R2.id.video_cover_layout, R2.id.add_video_img, R2.id.video_image_delete, R2.id.add_circle_cancel, R2.id.add_circle_submit, R2.id.add_circle_location})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.add_circle_cancel) {//退出
            finish();

        } else if (i == R.id.add_circle_submit) {//检查数据
            if (checkType == 0) {
                mPresenter.getCheckType(true);
            } else {
                checkData();
            }

        } else if (i == R.id.add_circle_location) {//定位
            MPermissionUtils.requestPermissionsResult(AddCircleActivity.this, 1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new MPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                    location();
                }

                @Override
                public void onPermissionDenied() {
                    MPermissionUtils.showTipsDialog(AddCircleActivity.this);
                }
            });

        } else if (i == R.id.video_image_delete) {//视频删除
            deleteVideo();

        } else if (i == R.id.add_video_img) {//选择视频
            chooseVideo();

        } else if (i == R.id.video_cover_layout) {//播放视频
            previewVideo();

        } else {
        }
    }

}
